package sub

import (
	"context"
	"quipus/internal/utils"
	"strings"

	"github.com/spf13/cobra"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"

	v1pb "quipus/proto/gen/api/v1"
)

var (
	username   string
	password   string
	tenantName string
)

func init() {
	RegisterCommonFlags(signinCmd)
	signinCmd.PersistentFlags().StringVarP(&username, "usename", "u", "", "user name")
	signinCmd.PersistentFlags().StringVarP(&password, "password", "p", "", "password ")
	signinCmd.PersistentFlags().StringVarP(&tenantName, "tenantName", "t", "", "tenant name ")

	AddCommand(signinCmd)
}

var signinCmd = &cobra.Command{
	Use:   "signin",
	Short: "Run the signin to login qpd",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := NewGrpcConnect(QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewAuthServiceClient(qconn)
		ctx := context.Background()

		var headerMD metadata.MD
		in := &v1pb.SignInRequest{Username: username, Password: password, TenantName: tenantName, NeverExpire: true}
		_, err := qclient.SignIn(ctx, in, grpc.Header(&headerMD))
		if err != nil {
			return err
		}

		if tokens := headerMD.Get("Authorization"); len(tokens) > 0 {
			authHeaderParts := strings.Fields(tokens[0])
			QpConfig.Token = authHeaderParts[1]

		}
		QpConfig.Username = username
		QpConfig.Password = password

		utils.WriteConfig("./etc/cli/qp.yaml", QpConfig)

		return nil
	},
}
